<template>
  <div class="test_content">
    <!-- 骨架屏 -->
    <mobile-skeleton 
      v-if="loading" 
      :showHeader="true"
      :showSearch="false"
      :showCards="false"
      :showTable="false"
      :showForm="true"
      :formFields="8"
      :showPagination="false"
    />
    
    <template v-else>
      <el-form ref="form" :model="form" label-width="120px" :rules="rules" :class="{'mobile-form': isMobile}">
        <div class="mobile-header" v-if="isMobile">
          <div class="back-btn" @click="handleBack">
            <img :src="backImg" />
          </div>
          <div class="page-title">创建培训</div>
          <div class="placeholder"></div>
        </div>

        <el-row :gutter="10" class="test_header" type="flex" align="middle" justify="space-around" style="padding: 10px" v-if="!isMobile">
          <el-col :span="22">
            <img :src="backImg" style="width: 25px; height: 25px; cursor: pointer" @click="handleBack" />
          </el-col>
          <el-col :span="2"></el-col>
        </el-row>

        <div class="form-container" :class="{'mobile-container': isMobile}">
          <el-row :gutter="20" style="margin-top: 20px">
            <el-row :gutter="10">
              <el-col :span="10" :sm="10" :xs="24">
                <el-form-item label="培训名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入培训名称"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <div class="form-section" v-if="isMobile">
              <div class="section-title">培训时间</div>
            </div>
            
            <el-row justify="space-between" class="date-picker-row">
              <el-form-item label="培训时间" :required="true" class="time-form-item" v-if="!isMobile">
                <el-col :span="1.5" :sm="1.5" :xs="11">
                  <el-form-item prop="start_time">
                    <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="form.start_time" type="datetime"
                      @change="startTime" placeholder="开始时间" class="responsive-date-picker">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="1.5" :xs="2" class="date-separator">-</el-col>
                <el-col :span="1.5" :sm="1.5" :xs="11">
                  <el-form-item prop="end_time">
                    <el-date-picker v-model="form.end_time" @change="endTime" type="datetime" placeholder="结束时间"
                      value-format="yyyy-MM-dd HH:mm:ss" class="responsive-date-picker">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-form-item>
              
              <div class="mobile-date-container" v-if="isMobile">
                <el-form-item prop="start_time" class="mobile-date-item">
                  <div class="date-label">开始时间</div>
                  <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="form.start_time" type="datetime"
                    @change="startTime" placeholder="请选择" class="mobile-date-picker">
                  </el-date-picker>
                </el-form-item>
                
                <el-form-item prop="end_time" class="mobile-date-item">
                  <div class="date-label">结束时间</div>
                  <el-date-picker v-model="form.end_time" @change="endTime" type="datetime" placeholder="请选择"
                    value-format="yyyy-MM-dd HH:mm:ss" class="mobile-date-picker">
                  </el-date-picker>
                </el-form-item>
              </div>
            </el-row>

            <el-row :gutter="10">
              <el-col :span="10" :sm="10" :xs="24">
                <div class="form-section" v-if="isMobile">
                  <div class="section-title">关联课程</div>
                </div>
                <el-form-item label="关联课程" prop="course" v-if="!isMobile">
                  <el-select v-model="form.course" placeholder="请选择关联课程" style="width: 100%"
                    @change="handleCheckQuestion(form.course)">
                    <el-option :label="item.label" :value="item.id" v-for="item in courseOptions" :key="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-select v-if="isMobile" v-model="form.course" placeholder="请选择关联课程" class="mobile-select"
                  @change="handleCheckQuestion(form.course)">
                  <el-option :label="item.label" :value="item.id" v-for="item in courseOptions" :key="item.id">
                  </el-option>
                </el-select>
              </el-col>
            </el-row>
            
            <el-row :gutter="10">
              <el-col :span="10" :sm="10" :xs="24">
                <div class="form-section" v-if="isMobile">
                  <div class="section-title">培训描述</div>
                </div>
                <el-form-item label="培训描述" prop="desc" v-if="!isMobile">
                  <el-input type="textarea" :rows="3" v-model="form.desc" placeholder="请输入内容"></el-input>
                </el-form-item>
                <el-input v-if="isMobile" type="textarea" :rows="4" v-model="form.desc" placeholder="请输入培训描述" class="mobile-textarea"></el-input>
              </el-col>
            </el-row>
            
            <el-row :gutter="10">
              <el-col :span="10" :sm="10" :xs="24">
                <div class="form-section" v-if="isMobile">
                  <div class="section-title">培训人员</div>
                  <div class="section-hint">请选择参与培训的人员</div>
                </div>
                <el-form-item label="培训人员" prop="user" class="user-tree-item" v-if="!isMobile">
                  <template>
                    <div class="post-tree">
                      <el-tree :data="userOptions" show-checkbox node-key="id" :default-checked-keys="defaultCheckedIds"
                        :props="defaultProps" ref="tree" :check-on-click-node="true">
                      </el-tree>
                    </div>
                  </template>
                </el-form-item>
                <div v-if="isMobile" class="mobile-tree-container">
                  <el-tree :data="userOptions" show-checkbox node-key="id" :default-checked-keys="defaultCheckedIds"
                    :props="defaultProps" ref="tree" :check-on-click-node="true">
                  </el-tree>
                </div>
              </el-col>
            </el-row>
            
            <el-row v-if="!isMobile">
              <el-col :span="10" :sm="10" :xs="24">
                <el-form-item class="submit-item">
                  <el-button type="primary" :style="{
                    backgroundColor: theme,
                    borderColor: theme,
                    fontWeight: 'bold',
                  }" @click="submitForm()">提交
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row v-if="isMobile" style="margin-top: 30px; margin-bottom: 40px;">
              <el-col :span="24">
                <el-button type="primary" class="mobile-submit-btn-inline" @click="submitForm()" :style="{
                  backgroundColor: theme,
                  borderColor: theme,
                  fontWeight: 'bold'
                }">提交</el-button>
              </el-col>
            </el-row>
          </el-row>
        </div>
      </el-form>
    </template>
    
    <el-dialog title="操作失败，以下知识点题目缺失，请补全题目后再创建或新增培训" :visible.sync="dialogTableVisible" class="responsive-dialog">
      <el-table :data="gridData" width="100%">
        <el-table-column property="name" label="知识点名称"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="handleKnowledge(scope.row)" :style="{ color: theme }">
              查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import backImg from "@/assets/images/back.png";
import { mapGetters, mapState } from "vuex";
import variables from "@/assets/styles/variables.scss";
import { trainDetail, addTrain, updateTrain, trainTestDetail } from "@/api/vadmin/train/train";
import { listUser } from "@/api/vadmin/permission/user";
import { questionStatistics } from "@/api/vadmin/exam/exam";
import { treeselectDeptUser } from "@/api/vadmin/permission/dept";
import { categoryTree } from "@/api/vadmin/course/course";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import MobileSkeleton from "@/components/MobileSkeleton";

export default {
  name: "newTrain",
  components: { Treeselect, MobileSkeleton },
  data() {
    return {
      dialogTableVisible: false,
      backImg: backImg,
      gridData: [],
      form: { user: [], desc: "" },
      userOptions: [],
      isIndeterminate: true,
      checkAll: false,
      checkedUsers: [],
      //课程分类
      courseOptions: [],
      defaultProps: {
        children: "users",
        label: "name",
      },
      defaultCheckedIds: [], // 用于存储默认选中的ID  
      // 表单校验
      rules: {
        name: [
          { required: true, message: "培训名称不能为空", trigger: "blur" },
        ],
        start_time: [
          { required: true, message: "培训开始时间不能为空", trigger: "blur" },
        ],
        end_time: [
          { required: true, message: "培训结束时间不能为空", trigger: "blur" },
        ],
        desc: [
          { required: true, message: "培训描述不能为空", trigger: "blur" },
        ],
        course: [
          { required: true, message: "关联课程不能为空", trigger: "blur" },
        ],
        user: [
          { required: true, message: "培训人员不能为空", trigger: "blur" },
        ],
      },
      screenWidth: document.body.clientWidth,
      loading: true,
      title: "新增培训",
    };
  },

  computed: {
    ...mapState(["settings"]),
    variables() {
      return variables;
    },
    theme() {
      return this.$store.state.settings.theme;
    },
    isMobile() {
      return this.screenWidth < 768;
    }
  },

  created() {
    this.getBasicData();
    if (this.$route.params.id !== undefined) {
      this.title = "编辑培训";
      trainTestDetail(this.$route.params.id).then(res => {
        this.getTrainData(res.id);
      })
    } else {
      this.loading = false;
    }
    
    // 监听屏幕宽度变化
    window.addEventListener('resize', this.handleResize);
  },
  
  beforeDestroy() {
    // 移除监听器
    window.removeEventListener('resize', this.handleResize);
  },
  
  methods: {
    handleResize() {
      this.screenWidth = document.body.clientWidth;
    },
    
    //表单重置
    reset() {
      this.form = {
        name: "",
        course: "",
        start_time: "",
        end_time: "",
        desc: "",
      };
      this.$refs.tree.setCheckedKeys([]);
    },
    //参考人员全选
    handleCheckAllChange(val) {
      var ids = this.userOptions.map((item) => {
        return item["id"];
      });
      this.form.user = val ? ids : [];
      this.isIndeterminate = false;
    },
    //人员选择
    handleCheckedUsersChange(value) {
      // let checkedCount = value.length;
      // this.checkAll = checkedCount === this.userOptions.length;
      // this.isIndeterminate =
      //   checkedCount > 0 && checkedCount < this.userOptions.length;
    },
    handleBack() {
      this.$router.push({ name: "Train" });
    },
    handleKnowledge(row) {
      let { href } = this.$router.resolve({
        path: "/course/knowledge",
        query: { knowledge: row.name },
      });
      window.open(href, "_blank");
    },
    /** 提交按钮 */
    submitForm() {
      this.form.user = this.$refs.tree
        .getCheckedNodes()
        .filter((item) => {
          return !item.users;
        })
        .map((item) => {
          return item.id;
        });

      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.$route.params.id != undefined) {
            this.$confirm("当前正在修改培训, 是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                updateTrain(this.form).then((res) => {
                  this.$message({
                    type: "success",
                    message: "修改成功!",
                  });
                });
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消修改",
                });
              });
          } else {
            this.$confirm("当前正在新增培训, 是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                this.form.state = 1; //设置默认开启培训
                addTrain(this.form).then((res) => {
                  this.reset();
                  this.$message({
                    type: "success",
                    message: "新建成功!",
                  });
                });
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消新增",
                });
              });
          }
        }
      });
    },
    getTrainData(id) {
      trainTestDetail(id).then((res) => {
        console.log(11, res)
        this.form = res;
        this.form.course = res.course.id;
        this.defaultCheckedIds = res.user.map((item) => {
          return item.id;
        });
        console.log(333, this.defaultCheckedIds)
        this.loading = false;
      });
    },
    startTime(val) {
      this.form.start_time = val
    },
    endTime(val) {
      this.form.end_time = val
    },
    getBasicData() {
      // 获取所有参考人员
      treeselectDeptUser({ page_size: 1000, page: 1 }).then((response) => {
        this.userOptions = this.handleUsersTree(response.results, "id");
        console.log(444, this.userOptions)
      });
      //所有课程
      categoryTree({ page_size: 1000, page: 1 }).then((response) => {
        delete response.children;
        this.courseOptions = response;
      });
    },
    handleCheckQuestion(course) {
      questionStatistics({ category: course, purpose: 1 }).then((response) => {
        const state = response.knowledge.question_state;

        if (response.count == 0 || state == 0) {
          // this.msgError(
          //   "创建培训失败，该课程或课程知识点下存在未添加试题的情况，请先新增试题"
          // );
          this.gridData = response.knowledge.no_question;
          this.dialogTableVisible = true;
          this.form.course = "";
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/.el-tabs__active-bar>>>.el-tabs__item {
  margin: 0 !important;
  border: 0;
}

.post-tree {
  border: 1px solid #dcdfe6;
}

/* 移动端样式 */
.mobile-form {
  .mobile-header {
    position: sticky;
    top: 0;
    z-index: 100;
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 50px;
    background-color: #fff;
    box-shadow: 0 1px 4px rgba(0,0,0,0.1);
    padding: 0 15px;
    margin: -10px -10px 15px;
    
    .back-btn {
      width: 40px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      
      img {
        width: 24px;
        height: 24px;
      }
    }
    
    .page-title {
      font-size: 17px;
      font-weight: 500;
    }
    
    .placeholder {
      width: 40px;
    }
  }
  
  .mobile-container {
    padding: 0 15px;
    padding-bottom: 30px; /* 减少底部空白 */
  }
  
  .form-section {
    margin: 20px 0 10px;
    
    .section-title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
      margin-bottom: 5px;
    }
    
    .section-hint {
      font-size: 12px;
      color: #909399;
      margin-bottom: 10px;
    }
  }
  
  .mobile-date-container {
    width: 100%;
    
    .mobile-date-item {
      margin-bottom: 15px;
      
      .date-label {
        font-size: 14px;
        color: #606266;
        margin-bottom: 8px;
      }
    }
    
    .mobile-date-picker {
      width: 100% !important;
      /deep/ .el-input__inner {
        height: 42px;
        border-radius: 8px;
        font-size: 15px;
      }
    }
  }
  
  .mobile-select {
    width: 100%;
    margin-bottom: 15px;
    
    /deep/ .el-input__inner {
      height: 42px;
      border-radius: 8px;
      font-size: 15px;
    }
  }
  
  .mobile-textarea {
    margin-bottom: 15px;
    
    /deep/ .el-textarea__inner {
      border-radius: 8px;
      padding: 12px;
      font-size: 15px;
      min-height: 100px;
    }
  }
  
  .mobile-tree-container {
    background-color: #f9f9f9;
    border-radius: 8px;
    padding: 12px;
    margin-bottom: 25px; /* 减少底部空白 */
    border: 1px solid #EBEEF5;
    max-height: 300px;
    overflow-y: auto;
    
    /deep/ .el-tree-node__content {
      height: 40px;
      padding-left: 8px;
      border-bottom: 1px solid #EBEEF5;
    }
    
    /deep/ .el-tree-node:last-child .el-tree-node__content {
      border-bottom: none;
    }
    
    /deep/ .el-tree-node__label {
      font-size: 15px;
    }
    
    /deep/ .el-checkbox__input {
      transform: scale(1.2);
    }
  }
  
  /* 添加内嵌提交按钮样式 */
  .mobile-submit-btn-inline {
    width: 100%;
    height: 44px;
    font-size: 16px;
    border-radius: 8px;
    margin-top: 15px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  }
  
  /* 备用：如果将来需要固定底部按钮，但调整位置 */
  .mobile-footer {
    position: fixed;
    bottom: 60px; /* 调整位置，避开底部菜单 */
    left: 0;
    right: 0;
    background: #fff;
    padding: 10px 15px;
    box-shadow: 0 -1px 4px rgba(0,0,0,0.1);
    z-index: 999;
    
    .mobile-submit-btn {
      width: 100%;
      height: 44px;
      font-size: 16px;
      border-radius: 8px;
    }
  }
  
  /deep/ .el-form-item__label {
    padding: 0 0 8px;
    line-height: 1.4;
    text-align: left;
    width: 100% !important;
    float: none;
  }
  
  /deep/ .el-form-item__content {
    margin-left: 0 !important;
    line-height: 1.4;
  }
  
  /deep/ .el-input__inner {
    height: 42px;
    border-radius: 8px;
    font-size: 15px;
  }
  
  /deep/ .el-form-item {
    margin-bottom: 18px;
  }
  
  /deep/ .responsive-dialog {
    width: 95% !important;
    border-radius: 12px;
    overflow: hidden;
    
    .el-dialog__header {
      padding: 15px;
      background-color: #f5f7fa;
    }
    
    .el-dialog__body {
      padding: 15px;
    }
    
    .el-dialog__headerbtn {
      width: 36px;
      height: 36px;
      font-size: 18px;
      top: 12px;
    }
  }
  
  /deep/ .el-message-box {
    width: 90% !important;
    border-radius: 12px;
    
    .el-message-box__header {
      padding-top: 15px;
    }
    
    .el-message-box__content {
      padding: 20px;
    }
    
    .el-message-box__btns {
      padding: 10px 15px 15px;
      
      button {
        height: 40px;
        font-size: 15px;
        min-width: 80px;
      }
    }
  }
  
  /deep/ .el-table {
    font-size: 14px;
    
    th {
      padding: 10px 0;
    }
    
    td {
      padding: 10px 0;
    }
    
    .cell {
      line-height: 24px;
    }
  }
}
</style>
